const userModel = require('../db/user')
const writeErr = require('../utils/writeErr')
const bcryptjs = require('bcryptjs')
const jwt = require('jsonwebtoken')
const path = require('path')
const { readFileSync } = require('fs')
const xy = require('../utils/xy')


module.exports = {
    // 获取用户信息
    async getinfo(req, resp) {
        // 获取传递过来的用户ID
        let { userId } = req.params
        // 根据用户Id获取用户其他信息
        // 用promise修改数据库操作
        try {
            let docs = await userModel.findOne({ _id: userId })
            if (!docs) {
                xy(resp, 405, '用户ID有误！')
                return
            }
            xy(resp, 200, '查询成功！', {
                username: docs.username,
                email: docs.email,
                tel: docs.tel,
                createdAt: +new Date(docs.createdAt),
                updatedAt: +new Date(docs.updatedAt)
            })
        } catch (err) {
            writeErr(err)
            xy(resp, 501, '系统繁忙，稍后再试！')
        }
    },
    // 登录处理
    async login(req, resp) {
        // 设置允许跨域的响应头
        // resp.setHeader('Access-Control-Allow-Origin', '*');
        let { username, password } = req.body
        if (!username || !password) {
            xy(resp, 401, '数据不能为空')
            return
        }
        // 用Promise修改数据库的操作

        try {
            let docs = await userModel.findOne({ username })
            // .then(docs => {
            if (!docs) {
                xy(resp, 403, '用户名或密码错误')
                return
            }
            if (!bcryptjs.compareSync(password, docs.password)) {
                xy(resp, 403, '用户名或密码错误')
                return
            }
            // 拼接配置文件路径
            let configFilePath = path.join(__dirname, '../', 'config', 'config.json');
            // 读取配置中的盐
            let salt = JSON.parse(readFileSync(configFilePath, 'utf-8')).tokenSalt
            xy(resp, 200, '登录成功', {
                token: jwt.sign({
                    userId: docs._id,
                    username: docs.username,
                    startTime: +new Date(),
                    expires: 7200 * 1000
                }, salt),
                userId: docs._id,
                username: docs.username
            })
        } catch (err) {
            writeErr(err)
            xy(resp, 501, '系统繁忙，稍后再试！')
        }
    },
    // 注册处理
    async register(req, resp) {
        let { username, password, email, tel } = req.body
        if (!username || !password || !email || !tel) {
            xy(resp, 401, '数据不能为空')
            return
        }
        // 用Promise处理数据库
        try {
            let docs = await userModel.findOne({ username })
            if (docs) {
                xy(resp, 402, '用户名被占用')
                return
            }
            try {
                docs = await userModel.insertMany({
                    username,
                    password: bcryptjs.hashSync(password, 10),
                    email,
                    tel
                })
                xy(resp, 200, '注册成功！')
            } catch (err) {
                writeErr(err)
                xy(resp, 501, '系统繁忙，稍后再试！')
            }
        } catch (err) {
            writeErr(err)
            xy(resp, 501, '系统繁忙，稍后再试！')
        }
    }
}